//
//  RootViewController.m
//  TableViewCellCustomizeBadge
//
//  Created by Kishikawa Katsumi on 10/05/05.
//  Copyright Kishikawa Katsumi 2010. All rights reserved.
//

#import "RootViewController.h"
#import "FeedCell.h"
#import "IconDownloader.h"
#import "NSString+XMLExtensions.h"

@implementation RootViewController

@synthesize data;
@synthesize imageDownloadsInProgress;
@synthesize imageCache;

#pragma mark -
#pragma mark View lifecycle

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = self.editButtonItem;
    
    self.data = [NSMutableArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"feed.plist" ofType:nil]];
    
    self.imageDownloadsInProgress = [NSMutableDictionary dictionary];
    self.imageCache = [NSMutableDictionary dictionary];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
    return YES;
}

#pragma mark -
#pragma mark Table cell image support

- (void)startIconDownloadForIndexPath:(NSIndexPath *)indexPath {
    IconDownloader *iconDownloader = 
    [imageDownloadsInProgress objectForKey:indexPath];
    if (!iconDownloader)  {
        iconDownloader = [[IconDownloader alloc] init];
        iconDownloader.imageURL = 
        [NSURL URLWithString:
         [[data objectAtIndex:indexPath.row] objectForKey:@"icon"]];
        iconDownloader.indexPathInTableView = indexPath;
        iconDownloader.delegate = self;
        [imageDownloadsInProgress setObject:iconDownloader forKey:indexPath];
        [iconDownloader startDownload];
        [iconDownloader release];   
    }
}

- (void)loadImagesForOnscreenRows {
    if ([data count] > 0) {
        NSArray *visiblePaths = [self.tableView indexPathsForVisibleRows];
        for (NSIndexPath *indexPath in visiblePaths) {
            UIImage *image = [imageCache objectForKey:indexPath];
            
            if (!image) {
                [self startIconDownloadForIndexPath:indexPath];
            }
        }
    }
}

- (void)iconDownloader:(IconDownloader *)downloader 
           didFinished:(UIImage *)image {
    [imageCache setObject:image forKey:downloader.indexPathInTableView];
    FeedCell *cell = 
    (FeedCell *)[self.tableView 
                 cellForRowAtIndexPath:downloader.indexPathInTableView];
    cell.icon = image;
    [cell setNeedsDisplay];
}

#pragma mark -
#pragma mark Deferred image loading (UIScrollViewDelegate)

- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView 
                  willDecelerate:(BOOL)decelerate {
    if (!decelerate) {
        [self loadImagesForOnscreenRows];
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    [self loadImagesForOnscreenRows];
}

#pragma mark -
#pragma mark Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return [data count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView 
         cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString *CellIdentifier = @"Cell";
    
    FeedCell *cell = 
    (FeedCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[FeedCell alloc] initWithStyle:UITableViewCellStyleDefault 
                                reuseIdentifier:CellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    
    NSDictionary *feed = [data objectAtIndex:indexPath.row];
	cell.title = [NSString decodeXMLCharactersIn:[feed objectForKey:@"title"]];
    cell.badgeNumber = [[feed objectForKey:@"unread_count"] integerValue];
    
    UIImage *icon = [imageCache objectForKey:indexPath];
    if (!icon) {
        if (self.tableView.dragging == NO && 
            self.tableView.decelerating == NO) {
            [self startIconDownloadForIndexPath:indexPath];
        }
        cell.icon = nil;            
    } else {
        cell.icon = icon;
    }
    
    return cell;
}

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        [data removeObjectAtIndex:indexPath.row];
        [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
    }   
}

- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath {
    [data exchangeObjectAtIndex:fromIndexPath.row withObjectAtIndex:toIndexPath.row];
}

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
    return YES;
}

#pragma mark -
#pragma mark Table view delegate

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

#pragma mark -
#pragma mark Memory management

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    NSArray *allDownloads = [self.imageDownloadsInProgress allValues];
    [allDownloads makeObjectsPerformSelector:@selector(cancelDownload)];
}

- (void)dealloc {
    [data release];
	[imageDownloadsInProgress release];
    [imageCache release];
    [super dealloc];
}

@end
